"""
一、写一个文件传输服务器和客户端，用于在两台机之间传输文件

1. 通过命令行参数指定ip和端口
2. 每次只传输一个文件
"""

import sys
import os
import socket


def transfer(sock, buffer):
    bs = 16384
    while True:
        chunk = buffer.read(bs)
        if not chunk:
            break
        sock.send(chunk)


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print('usage: %s ip port file' % os.path.basename(sys.argv[0]))
        exit(1)
    ip = sys.argv[1]
    port = int(sys.argv[2])
    file = sys.argv[3]

    # 打开文件
    try:
        f = open(file, 'rb')
    except Exception as e:
        print(e)
        exit(1)

    # 连接服务器，传输数据
    sock = socket.socket()
    sock.connect((ip, port))
    transfer(sock, f)

    # 清理操作
    f.close()
    sock.close()
